package com.powernode.listener;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.powernode.constant.QueueConstant;
import com.powernode.model.SmsModel;
import com.powernode.service.SmsLogService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 内容:
 * 作者: cy
 */
@Component
@Slf4j
public class AliSmsListener {

    @Autowired
    private IAcsClient acsClient;

    @Autowired
    private SmsLogService smsLogService;

    @RabbitListener(queues = QueueConstant.PHONE_SEND_QUEUE, concurrency = "3-5")
    public void handlerAliSmsMsg(Message message, Channel channel) {
        // 那到消息
        String msgStr = new String(message.getBody());
        SmsModel smsModel = JSON.parseObject(msgStr, SmsModel.class);
        SendSmsResponse sendSmsResponse = realSendMsg(smsModel);
        // 记录记录库 方便后期核算钱
        smsLogService.saveSmsLog(sendSmsResponse, smsModel);
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private SendSmsResponse realSendMsg(SmsModel smsModel) {
        SendSmsRequest request = new SendSmsRequest();
        request.setMethod(MethodType.POST);
        request.setPhoneNumbers(smsModel.getPhoneNumbers());
        request.setSignName(smsModel.getSignName());
        request.setTemplateCode(smsModel.getTemplateCode());
        request.setTemplateParam(smsModel.getTemplateParam());
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        System.out.println(sendSmsResponse);
        return sendSmsResponse;
    }


}
